<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>消息</title>
    <style type="text/css">
        * {margin:0;padding:0;}
        ul,ol,li {list-style:none;}
        .list-box .item {padding-left:4vw;display:flex;align-items:center;justify-content:space-between;}
        .item-left {width:12vw;height:12vw;position:relative;}
        .item-left .item-head {width:100%;height:100%;border-radius:50%;background-size:cover;background-position:center;background-color:#ccc;}
        .item-left .head-point {width:1.6vw;height:1.6vw;background-color:#f00;border-radius:50%;position:absolute;top:-2px;right:-2px;}
        .item-right {width:77vw;height:12vw;display:flex;flex-direction:column;justify-content:space-around;line-height:1;border-bottom:1px solid #f4f4f4;padding:3vw 4vw 3vw 0;}
        .item-name {font-size:14px;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
        .item-word {font-size:12px;color:#999;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
        [v-cloak]{display:none !important}
    </style>
</head>
<body>
    <div id="app">
        <template v-if="getList.length > 0">
            <ul class="list-box">
                <template v-for="(item, i) in getList">
                    <li class="item" @click="goChat(item.to_uid)">
                        <div class="item-left">
                            <div class="item-head" :style="{backgroundImage:'url('+item.avatar+')'}"></div>
                            <!-- <i class="head-point"></i> -->
                        </div>
                        <div class="item-right">
                            <p class="item-name">{{item.nickname}}</p>
                            <template v-if="item.msg_type=='text'">
                                <p class="item-word">{{item.content}}</p>
                            </template>
                            <template v-else="item.msg_type=='img'">
                                <p class="item-word">图片</p>
                            </template>
                            <template v-else>
                                <p class="item-word"></p>
                            </template>
                        </div>
                    </li>
                </template>
            </ul>
        </template>
        <template v-else>
            <p style="text-align:center; padding: 10px;">
                暂无用户消息
            </p>
        </template>
    </div>
</body>
<script src="/chat/js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/iscroll.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/exif.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/upload.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/vue.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/moment.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/chat/js/moment-with-locales.js" type="text/javascript" charset="utf-8"></script>
<!-- <script src="/chat/js/vconsole.min.js" type="text/javascript" charset="utf-8"></script> -->
<script type="text/javascript">
var app = new Vue({
    el:"#app",
    data:{
        list:{:json_encode($list)},
    },
    computed:{
        getList: function(){
            var listNew = [];
            return this.list.sort(function(a,b){
                return b.time- a.time;
            });
            return this.list;
        },
    },
    methods:{
        timeStr: function(t){
            moment.locale('zh-cn');
            // var str = moment(t*1000).format('YYYY年MM月DD日 HH:mm:ss')
            var str = moment(t*1000).format('LLL')
            return str;
        },
        goChat: function(to_uid){
            location.href = '../../socket.php/chat/chat.html?to_uid='+to_uid;
        }
    }
});
var ws = null;
var wsStatus = false;
var lockReconnect = false;
var reconnectTime = null;

function reconnectWs() {
    if(wsStatus || lockReconnect){
        return;
    }
    lockReconnect = true;
    reconnectTime = setInterval(function () {
        createWebSocket();
    }, 3000);
}
function createWebSocket() {
    ws = new WebSocket("ws://"+location.host+":7584");
    initEventHandle();
}
function sayId() {
    return 'msg'+(new Date().getTime())+Math.ceil(Math.random()*1000);
}

function wsSendMsg(data) {
    console.log('ws 发送消息', data);
    data.say_id = sayId();
    ws.send(JSON.stringify(data));
}

function initEventHandle() {
    ws.onopen = function(){
        wsStatus = true;
        if(lockReconnect){
            alert('连接成功');
        }
        lockReconnect = false;
        if(reconnectTime){
            clearInterval(reconnectTime);
        }
        setInterval(function () {
            if(wsStatus){
                var data = {"event":"ping", "say_id":sayId()};
                // sendMessage(data);
                // ws.send(JSON.stringify(data));
                wsSendMsg(data);
            }
        }, 5000);
    };

    // 服务端主动推送消息时会触发这里的onmessage
    ws.onmessage = function(e){
        console.log('接收消息', e.data);
        // json数据转换成js对象
        var data = eval("("+e.data+")");
        var event = data.event || '';
        switch(event){
            // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
            case 'init':
                // sendMessage({'event':'init', 'uid':user_id});
                // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
                $.post("{:U('../socket.php/chat/bind')}", {client_id: data.client_id}, function(data){}, 'json');
                break;
            case 'say_res':
                if(!data.status){
                    alert('发送失败');
                }else{
                    
                }
                break;
            case 'msg':
                var toMsg = app.list.filter(function(e){return e.to_uid==data.from_uid});
                if(toMsg.length >0){
                    toMsg = toMsg[0];
                    toMsg.time = data.time;
                    toMsg.msg_type = data.msg_type;
                    toMsg.content = data.content;
                }else{
                    app.list.push({to_uid: data.from_uid, msg_type: data.msg_type, content: data.content, time: data.time, nickname: data.nickname, avatar: data.avatar});
                }
                break;
            case 'pong':
                break;
            // 当mvc框架调用GatewayClient发消息时直接alert出来
            default :
                alert(e.data);
        }
    };

    ws.onclose = function(evt){
        wsStatus = false;
        console.log('WebSocketClosed!');
        if(!lockReconnect){
            // 非重连
            alert('断开连接');
        }
        reconnectWs();
    };

    ws.onerror = function(evt){
        wsStatus = false;
        console.log('WebSocketError!', evt);
        if(!lockReconnect){
            // 非重连
            alert('连接失败');
        }
        reconnectWs();
    };
}
createWebSocket();
</script>
</html>